// ChildModal.vue
<template>
  <div>
    <el-dialog
      v-if="isVisible"
      :visible.sync="isVisible"
      title="配置血缘关系"
      @close="handleClose"
      fullscreen
      class="full-width-dialog"
    >
      <div>
        <!-- 步骤条 -->
        <div class="top">
          <el-steps :active="activeStep" finish-status="success">
            <el-step
              v-for="step in steps"
              :key="step"
              :title="getStepTitle(step)"
              :status="getStepStatus(step)"
            ></el-step>
          </el-steps>
        </div>
        <!-- 内容 -->
        <div class="bottom flex">
          <div class="b-left">
            <!-- 步骤内容盒子 -->
            <div v-for="index in activeStep" :key="index" :class="['step-box']">
              <div
                v-if="index === 1"
                @click="handleBoxClick(index)"
                class="dataType"
              >
                <div class="text">
                  数据源头
                  <span class="svg-container">
                    <svg-icon icon-class="数据源" class="icon" />
                  </span>
                </div>
              </div>
              <div
                v-else-if="index === 2"
                @click="handleBoxClick(index)"
                class="dataType"
              >
                <div class="text">
                  全量层
                  <span class="svg-container">
                    <svg-icon icon-class="全量数据" class="icon" />
                  </span>
                </div>
              </div>
              <div
                v-else-if="index === 3"
                @click="handleBoxClick(index)"
                class="dataType"
              >
                <div class="text">
                  核心层
                  <span class="svg-container">
                    <svg-icon icon-class="核心数据" class="icon" />
                  </span>
                </div>
              </div>
              <div
                v-else-if="index === 4 && showStepFourAndFive"
                @click="handleBoxClick(index)"
                class="dataType"
              >
                <div class="text">
                  主题层
                  <span class="svg-container">
                    <svg-icon icon-class="主题数据" class="icon" />
                  </span>
                </div>
              </div>
              <div
                v-else-if="index === 5 && showStepFourAndFive"
                @click="handleBoxClick(index)"
                class="dataType"
              >
                <div class="text">
                  数据服务
                  <span class="svg-container">
                    <svg-icon icon-class="数据服务" class="icon" />
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="b-right">
            <div
              id="x6modelAdd"
              ref="AddGraphContainer"
              style="width: 80vw; height: 100vh;"
            />
          </div>
        </div>
      </div>

      <div class="dialogTwo">
        <el-dialog
          class="log"
          title="配置库表关系"
          v-if="innerVisible"
          :visible.sync="innerVisible"
          append-to-body
        >
          <div class="formDialog">
            <el-form
              label-position="left"
              label-width="80px"
              :model="formLabelAlign"
            >
              <el-form-item label="库名称">
                <el-select
                  v-model="formLabelAlign.store"
                  filterable
                  placeholder="请选择库"
                  @change="storeChange"
                >
                  <el-option
                    v-for="item in storeOptions"
                    :key="item.id"
                    :label="item.name ? item.name : item.apiName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="表名称">
                <el-select
                  v-model="formLabelAlign.table"
                  placeholder="请选择表"
                  filterable
                  @change="tableChange"
                >
                  <el-option
                    v-for="item in tableOptions"
                    :key="item.id"
                    :label="item.tableName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <div class="footer">
                  <el-button type="primary" @click="cancel">取消</el-button>
                  <el-button @click="sumbitForm">确定</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-dialog>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Graph } from '@antv/x6'
//     查表             数据源头          全量层              核心层              主题层              数据服务
import {
  getTableList,
  getSourceList,
  getSourceListByHive,
  getSourceListByCore,
  getSourceListByTopic,
  getMarketApiList
} from '@/api/dataKinship/index.js'
export default {
  name: 'ChildModal',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  created() {
    console.log('ChildModal created')
  },
  data() {
    return {
      innerVisible: false,
      isVisible: this.value,
      activeStep: 1,
      steps: [1, 2, 3, 4, 5],
      stepsCompleted: [false, false, false, false, false],
      showStepFourAndFive: false,
      graphAdd: null,
      x6List: {
        // cellList: [
        //   {
        //     tableId: '1746418493533818881',
        //     tableName: 'T_ST_DYZ_ZMKDSJCL',
        //     tableDescription: '打渔张泵站闸门开度数据处理表',
        //     x: 100,
        //     y: 100
        //   },
        //   {
        //     tableId: '1746418490614583298',
        //     tableName: 'T_D_STAT_LS_FB_RECORD',
        //     tableDescription: '泵站机组开关机记录表',
        //     x: 100,
        //     y: 300
        //   },
        //   {
        //     tableId: '1751844592089243650',
        //     tableName: 'T_ST_DYZ_EDGNBVFTTY',
        //     tableDescription: '根据15标数据统计来的',
        //     x: 100,
        //     y: 500
        //   },
        //   {
        //     tableId: '1751844591900499970',
        //     tableName: 'T_ST_DYZ_ZDKJITHHL',
        //     tableDescription: '棘洪滩水库闸门数据处理表',
        //     x: 500,
        //     y: 500
        //   }
        // ],
        // edgeList: [
        //   {
        //     sourceId: '1746418493533818881',
        //     sourceName: 'T_ST_DYZ_ZMKDSJCL',
        //     targetId: '1746418490614583298',
        //     targetName: 'T_D_STAT_LS_FB_RECORD',
        //     sourcePort: 'port3',
        //     targetPort: 'port1',
        //     sourceCell: null,
        //     targetCell: null
        //   },
        //   {
        //     sourceId: '1746418490614583298',
        //     sourceName: 'T_D_STAT_LS_FB_RECORD',
        //     targetId: '1751844592089243650',
        //     targetName: 'T_ST_DYZ_EDGNBVFTTY',
        //     sourcePort: 'port3',
        //     targetPort: 'port1',
        //     sourceCell: null,
        //     targetCell: null
        //   },
        //   {
        //     sourceId: '1751844592089243650',
        //     sourceName: 'T_ST_DYZ_EDGNBVFTTY',
        //     targetId: '1751844591900499970',
        //     targetName: 'T_ST_DYZ_ZDKJITHHL',
        //     sourcePort: 'port6',
        //     targetPort: 'port5',
        //     sourceCell: null,
        //     targetCell: null
        //   }
        // ]
        cellList: [],
        edgeList: []
      },
      newNodeList: [],
      formLabelAlign: {
        store: '', //库
        table: '' //表
      },
      storeOptions: [],
      tableOptions: []
    }
  },
  watch: {
    value(val) {
      this.isVisible = val
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getX6Echarts()
    })
  },
  methods: {
    handleClose() {
      this.isVisible = false
      this.$emit('update:value', false)
    },
    handleBoxClick(step) {
      console.log(step, 'step')
      let tableDescription = this.getStepTitle(step)
      if (!this.stepsCompleted[step - 1]) {
        this.$set(this.stepsCompleted, step - 1, true)
        if (step === 3) {
          this.showStepFourAndFive = true // 点击第三步时显示第四和第五步
          this.activeStep = 5 // 直接设置激活步骤为第五步
        } else if (step === 5) {
          this.$set(this.stepsCompleted, 3, true)
        } else if (step < this.steps.length) {
          this.activeStep = step + 1
        }
        if (step <= 4) {
          const addNode = {
            tableId: '999' + step,
            tableName: 'xxxxx' + step,
            tableDescription: tableDescription,
            y: step * 150 - 80
          }
          this.addNewNode(addNode)
          this.x6List.cellList.push(addNode)
          if (this.x6List.cellList.length > 1) {
            this.addNewEdge(step)
          }
        } else if (step == 5) {
          const stepLen = this.x6List.cellList.length
          let Y = stepLen == 3 ? 520 : 670
          const addNode = {
            tableId: '999' + step,
            tableName: 'xxxxx' + step,
            tableDescription: tableDescription,
            y: Y
          }
          this.addNewNode(addNode)
          this.x6List.cellList.push(addNode)
          if (this.x6List.cellList.length > 1) {
            this.addNewEdge(step)
          }
        }
      }
    },
    getStepStatus(step) {
      return this.stepsCompleted[step - 1] ? 'finish' : 'wait'
    },
    getStepTitle(step) {
      if (step == 1) {
        return '数据源头'
      } else if (step == 2) {
        return '全量层'
      } else if (step == 3) {
        return '核心层'
      } else if (step == 4) {
        return '主题层'
      } else if (step == 5) {
        return '数据服务'
      }
    },
    getX6Echarts() {
      if (this.graphAdd) {
        this.graphAdd.dispose()
      }
      const container = this.$refs.AddGraphContainer
      this.graphAdd = new Graph({
        container,
        panning: true, //画布是否可拖动
        interacting: true, //是否可交互
        connecting: {
          allowBlank: false,
          allowLoop: false
          // allowNode: false
        }
      })
      Graph.registerNode(
        'custom-node',
        {
          width: 200,
          height: 60,
          attrs: {
            body: {
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: 'rgba(95,149,255,0.05)',
              refWidth: 1,
              refHeight: 1
            },
            image: {
              'xlink:href':
                'https://img0.baidu.com/it/u=1042886901,3501250760&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
              width: 30,
              height: 30,
              x: 12,
              y: 14
            },
            // title: {
            //   text: '',
            //   refX: 60,
            //   refY: 14,
            //   fill: 'rgba(0,0,0,0.85)',
            //   fontSize: 15,
            //   'text-anchor': 'start'
            // },
            text: {
              text: '',
              refX: 60,
              refY: 24,
              fontSize: 18,
              fill: 'rgba(0,0,0,0.6)',
              'text-anchor': 'start'
            }
          },
          markup: [
            {
              tagName: 'rect',
              selector: 'body'
            },
            {
              tagName: 'image',
              selector: 'image'
            },
            {
              tagName: 'text',
              selector: 'title'
            },
            {
              tagName: 'text',
              selector: 'text'
            }
          ]
        },
        true
      )
      this.graphAdd.on('node:click', ({ node, view }) => {
        // console.log('点击了NOde', node, 'view', view)
        let id = node.data.tableId
        if (id == '9991') {
          console.log('9991')
          getSourceList().then((res) => {
            console.log(res, '数据源头')
            this.storeOptions = res.data.data
          })
        } else if (id == '9992') {
          getSourceListByHive().then((res) => {
            console.log(res, '全量层')
            this.storeOptions = res.data.data
          })
        } else if (id == '9993') {
          getSourceListByCore().then((res) => {
            console.log(res, '核心层')
            this.storeOptions = res.data.data
          })
        } else if (id == '9994') {
          getSourceListByTopic().then((res) => {
            console.log(res, '主题层')
            this.storeOptions = res.data.data
          })
        } else if (id == '9995') {
          getMarketApiList().then((res) => {
            console.log(res, '数据服务')
            this.storeOptions = res.data.data
          })
        }
        this.innerVisible = true
      })
    },
    addNewNode(newarr) {
      const newNodeData = {
        x: 300,
        y: Number(newarr.y),
        width: 300,
        height: 60,
        shape: 'custom-node',
        data: {
          tableId: newarr.tableId,
          label: newarr.tableName
        },
        attrs: {
          text: {
            text: newarr.tableDescription
          }
        },
        ports: {
          groups: {
            // 输入链接桩群组定义
            in: {
              position: 'top',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff'
                }
              }
            },
            // 输出链接桩群组定义
            out: {
              position: 'bottom',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff'
                }
              }
            },
            topLeft: {
              position: 'left',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff'
                }
              }
            },
            bottomRight: {
              position: 'right',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff'
                }
              }
            }
          },
          items: [
            {
              id: 'port1',
              group: 'in'
            },
            {
              id: 'port2',
              group: 'in'
            },
            {
              id: 'port3',
              group: 'out'
            },
            {
              id: 'port4',
              group: 'out'
            },
            {
              id: 'port5',
              group: 'topLeft'
            },
            {
              id: 'port6',
              group: 'bottomRight'
            }
          ]
        }
      }

      // const newNode = this.graph.createNode(newNodeData)
      const newNode = this.graphAdd.addNode(newNodeData)
      // console.log(a, 'newADD')
      this.newNodeList.push(newNode)
    },
    addNewEdge(step) {
      const edgeList = this.createEdgesFromCells(this.x6List.cellList)
      console.log(edgeList, 'edgelll')
      edgeList.forEach((item) => {
        this.newNodeList.forEach((newCellItem) => {
          if (item.sourceId === newCellItem.data.tableId) {
            item.sourceCell = newCellItem.id
          }
          if (item.targetId === newCellItem.data.tableId) {
            item.targetCell = newCellItem.id
          }
        })
      })
      edgeList.map((v, i) => {
        this.graphAdd.addEdge({
          source: { cell: v.sourceCell, port: v.sourcePort },
          target: { cell: v.targetCell, port: v.targetPort }
        })
      })
    },
    createEdgesFromCells(cells) {
      const edges = []
      for (let i = 0; i < cells.length - 1; i++) {
        const sourceCell = cells[i]
        const targetCell = cells[i + 1]
        edges.push({
          sourceId: sourceCell.tableId,
          sourceName: sourceCell.tableName,
          targetId: targetCell.tableId,
          targetName: targetCell.tableName,
          sourcePort: 'port3',
          targetPort: 'port1',
          sourceCell: null,
          targetCell: null
        })
      }
      return edges
    },
    cancel() {
      this.formLabelAlign = {
        store: ''
      }
      this.options = []
      this.innerVisible = false
    },
    sumbitForm() {
      this.innerVisible = false
    },
    storeChange(val) {
      console.log(val, '目前选中的值')
      getTableList({ sourceId: val }).then((res) => {
        console.log(res, '表的数据')
        this.tableOptions = res.data.data
      })
    },
    tableChange(val) {
      console.log(val, '点击了表')
    }
  }
}
</script>
<style lang="scss">
.full-width-dialog {
  .el-dialog {
    width: 100% !important;
  }
  .flex {
    display: flex;
  }
  .top {
    height: 10vh;
  }
  .bottom {
    height: 80vh;
  }
  .b-left {
    height: 100%;
    width: 20vw;
  }

  .step-box {
    height: 18%;
    width: 20vw;
    transition: all 0.3s ease;
    cursor: pointer;
  }

  .active-box {
    border: 2px solid #409eff;
  }
  .dataType {
    height: 100%;
    width: 100%;
    border: 1px solid #ebebeb; /* 边框样式 */
    border-radius: 4px; /* 圆角 */
    padding: 20px; /* 内边距 */
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1); /* 阴影效果 */
    background-color: #ffffff; /* 背景色 */
    .text {
      height: 20px;
      line-height: 20px;
      font-size: 20px;
    }
    .svg-container {
      display: block;
      text-align: center;
    }
    .icon {
      font-size: 4.1667vw;
      text-align: center;
    }
  }
  #x6modelAdd {
    background-image: url('../../../../../assets/dataRelationBg.png');
    background-size: cover;
  }
}
.log {
  .el-dialog {
    width: 40% !important;
  }
  .formDialog {
    position: relative;

    height: 200px;
  }
  .footer {
    position: absolute;
    margin-top: 20px;
    right: 2%;
  }
}
</style>
